<!--用户管理-->
<template>
  <div>
    <Modal v-model="modal.show"  :loading="modal.loading" :title="modal.title"  :mask-closable="false" :footer-hide=true width="800px" :closable="false">
      <Row>
        <Col span="8"><Input clearable :placeholder="$t('user_account')" v-model="table.param.where.userAccount"/></Col>
        <Col span="8"><Input clearable :placeholder="$t('user_name')" v-model="table.param.where.userName"/></Col>
        <Button type="primary" :Title="$t('search')" icon="ios-search" shape="circle" @click="getData" style="margin-left: 10px"></Button>
        <Button type="success" :disabled="!selects"  :Title="$t('add_user_to_group')" icon="md-person-add" shape="circle" @click="addUserToGroup" style="margin-left: 10px"></Button>
        <Button type="error"  :disabled="!selects" :Title="$t('remove_device_from_Intercom')" icon="md-remove" shape="circle" @click="removeUserFromZzd" style="margin-left: 10px"></Button>
        <Button type="primary" :Title="$t('device_manage')" icon="md-train" shape="circle" @click="deviceManager" style="margin-left: 10px"></Button>
        <Col span="8"></Col>
      </Row>
      <!--      <Card>-->
      <Table border ref="zzdUserTable" :columns="table.columns" :data="table.data" :loading="table.loading" @on-row-click="rowclick"
             @on-selection-change="onSelectionChange">
        <template slot-scope="{ row, index }" slot="action">
          <Button type="default" :Title="$t('delete')" icon="md-trash" style="margin-right: 3px" @click="table.remove(row)"></Button>
        </template>
        <template slot-scope="{ row, index }" slot="online">
          <span v-if="row.userOnline===1" style="color: green" >{{$t('online')}}</span>
          <span v-if="!(row.userOnline===1)" style="color: red">{{$t('offline')}}</span>
        </template>
        <template slot-scope="{ row, index }" slot="status">
          <span v-if="row.userStatus===1" style="color: green" >{{$t('enable')}}</span>
          <span v-if="!(row.userStatus===1)" style="color: red">{{$t('disable')}}</span>
        </template>
      </Table>
      <TopnavPage v-model="table.param.page" @changePage="changePage"></TopnavPage>
      <!--      </Card>-->
      <Form>
        <FormItem>
          <div style="float: right;">
            <Button @click="close">{{$t('close')}}</Button>
          </div>
        </FormItem>
      </Form>
      <ZzdDevice5gSelect ref="zzdDevice5gSelect"></ZzdDevice5gSelect>
    </Modal>


  </div>
</template>
<script>
import TopnavPage from '_c/topnav/TopnavPage'
import ZzdDevice5gSelect from "@/view/zzd/ZzdDevice5gSelect";
import Zzd from "@/api/Zzd"
import Device from "@/api/Device"
import {apiResult} from "@/libs/util";
export default {
  name:"ZzdUserManager",
  components:{TopnavPage,ZzdDevice5gSelect},
  data(){
    return{
      api: new Zzd(),
      deviceApi: new Device(),
      modal:{
        show:false,loading:false,title:this.$t("intercom_registered_user_manage"),
      },
      table:{
        data:[],
        loading:false,
        columns:[
          {type: 'selection',width:60,align:'center'},
          { title: this.$t("user_account"), key: 'userAccount', sortable: true, width: 200,ellipsis:true,tooltip:true,tooltipTheme:'light' },
          { title: this.$t("user_name"), key: 'userName', sortable: true, width: 200,ellipsis:true,tooltip:true,tooltipTheme:'light' },
          { title: this.$t("user_status"), key: 'userStatus', sortable: true, width: 100,slot: 'status',ellipsis:true,tooltip:true,tooltipTheme:'light' },
          { title: this.$t("online"),key: 'userOnline', sortable: true, width: 100,slot: 'online',ellipsis:true,tooltip:true,tooltipTheme:'light' },
          { title: this.$t("group_names"), key: 'groupNames', sortable: true, width: 200 },],
        param:{
          page:{pages: 1,size: 10,total: 0, current: 1,},
          where:{userOnline:null,userAccount:null,userName:null},
        },
        selection:[],
        view(row){},
        edit(row){},
        remove(row){},
      },
      orginColumns:[],
      groupId: null,
      selects:false,
    }
  },
  methods:{
    /**
     * 从Zzd中删除用户，非本系统的用户不能删除
     */
    removeUserFromZzd(){
      if (!this.table.selection || this.table.selection.length===0){
        this.$Message.error(this.$t('no_select_data'))
        return;
      }
      //移除
      this.$Modal.confirm({title: this.$t('delete_confirm'),content: "<p>"+this.$t('delete_make_sure_by_select')+"</p",
        onOk: () => {
          let params=[];
          //console.log(this.table.selection);
          let talkAccount;
          this.table.selection.forEach((item)=>{
            //console.log(item.userAccount);
            if (!!item.userAccount){
              talkAccount = !talkAccount?item.userAccount:talkAccount+","+item.userAccount;
            }
          })
          //console.log(talkAccount);
          if (!talkAccount) {
            this.$Message.error("Data from different systems cannot be removed！")
            return;
          }
          this.deviceApi.queryListWhere(JSON.stringify({talkAccount: talkAccount})).then(res=>{
              apiResult(res.data,false,result=>{
                if (!result.data || result.data.length === 0){
                  this.$Message.error("Data from different systems cannot be removed！")
                  return;
                }
                //console.log(">>>>>>ZzdUserManager.removeUserFromZzd: selection=%o",this.table.selection);
                //console.log(">>>>>>ZzdUserManager.removeUserFromZzd: res.data.data=%o",res.data.data);
                this.table.selection.forEach((u)=>{
                  result.data.forEach((d)=>{
                    if (!!u.userAccount && !!d.talkAccount && u.userAccount===d.talkAccount){
                      params.push(
                        {
                          userAccount:u.userAccount,
                          userId:u.userId,
                          userName:u.userName
                        })
                    }
                  })
                })
                if (params.length === 0) {
                  this.$Message.error("Data from different systems cannot be removed！")
                  return;
                }

                const msg = this.$Message.loading({content: this.$t('wait_dispose_message'),duration: 10});
                this.api.deleteUsers(JSON.stringify(params)).then((res1)=>{
                  setTimeout(msg, 100); //关闭正加载条
                  this.$refs.zzdUserTable.selectAll(false);//取消选择
                  apiResult(res1.data,true,result1=>{
                    //this.$Message.success(this.$t("delete_succeed"))
                    this.getData();
                    if (this.table.data.length === 0){
                      if (this.table.param.page.current > 1){
                        this.table.param.page.current = 1;
                        this.getData();
                      }
                    }
                  })
                });
              })
            /*if (res.data.code==0){
              if (!res.data.data || res.data.data.length === 0){
                this.$Message.error("Data from different systems cannot be removed！")
                return;
              }
              //console.log(">>>>>>ZzdUserManager.removeUserFromZzd: selection=%o",this.table.selection);
              //console.log(">>>>>>ZzdUserManager.removeUserFromZzd: res.data.data=%o",res.data.data);
              this.table.selection.forEach((u)=>{
                res.data.data.forEach((d)=>{
                  if (!!u.userAccount && !!d.talkAccount && u.userAccount===d.talkAccount){
                    params.push(
                      {
                        userAccount:u.userAccount,
                        userId:u.userId,
                        userName:u.userName
                      })
                  }
                })
              })
              if (params.length === 0) {
                this.$Message.error("Data from different systems cannot be removed！")
                return;
              }

              const msg = this.$Message.loading({content: this.$t('wait_dispose_message'),duration: 10});
              this.api.deleteUsers(JSON.stringify(params)).then((res1)=>{
                setTimeout(msg, 100); //关闭正加载条
                this.$refs.zzdUserTable.selectAll(false);//取消选择
                apiResult(res1.data,true,result=>{
                  this.$Message.success(this.$t("delete_succeed"))
                  this.getData();
                  if (this.table.data.length === 0){
                    if (this.table.param.page.current > 1){
                      this.table.param.page.current = 1;
                      this.getData();
                    }
                  }
                })
              });
            }else{
              console.log(res.data.msg)
            }*/

          })
          return;
        },
        onCancel:()=>{}
      });
    },
    deviceManager(){
      this.$refs.zzdDevice5gSelect.openDialog(()=>{
        this.getData();
      });
    },
    /**
     *  加用户用户到群组
     */
    addUserToGroup(){
      if (!this.table.selection || this.table.selection.length===0){
        this.$Message.error(this.$t('no_select_data'))
        return;
      }
      let params=[];
      let talkAccount;
      this.table.selection.forEach((item)=>{
        if (!!item.userAccount){
          talkAccount = !talkAccount?item.userAccount:talkAccount+","+item.userAccount;
        }
      })
      if (!talkAccount) {
        this.$Message.error("Data from different systems cannot be removed！")
        return;
      }
      this.deviceApi.queryListWhere(JSON.stringify({talkAccount: talkAccount})).then(res=>{
          apiResult(res.data,false,result=>{
            console.log("ZzdUserManager.removeUserFromZzd result=%o",result);
            if (!res.data.data || res.data.data.length === 0){
              this.$Message.error("Data from different systems cannot be removed！")
              return;
            }
            talkAccount=null;
            this.table.selection.forEach((u)=>{
              res.data.data.forEach((d)=>{
                if (!!u.userAccount && !!d.talkAccount && u.userAccount===d.talkAccount){
                  talkAccount = !talkAccount?u.userAccount:talkAccount+","+u.userAccount;
                }
              })
            })
            if (!talkAccount) {
              this.$Message.error("Data from different systems cannot be removed！")
              return;
            }
            const msg = this.$Message.loading({content: this.$t('wait_dispose_message'),duration: 10});
            this.api.addUserToGroup(JSON.stringify({groupId:this.groupId,userId:talkAccount})).then(res1=>{
              setTimeout(msg, 100); //关闭正加载条
              this.$refs.zzdUserTable.selectAll(false);//取消选择

              apiResult(res1.data,true,result=>{
                  this.getData();
                },
              );
            });
          });
      })
    },

    onSelectionChange(selection){
      this.selects = !!selection && selection.length > 0;
      this.table.selection = selection;
    },
    changePage(){
      this.getData();
    },
    getData(){
      const _this = this;
      /** 生成查询条件 */
      this.table.loading = true;
      console.log("ZzdUserManager.getData()：param=%o",this.table.param)
      this.api.queryUserPage(JSON.stringify(this.table.param)).then(res => {

        this.table.loading = false;
        this.table.data = [];//这里不要赋为 null, 当没有数据时一定会报错
        console.log("ZzdUserManager.getData()：res=%o",res)
        apiResult(res.data,false,result=>{
          this.$refs.zzdUserTable.selectAll(false);//取消选择
          this.table.param.page.total = res.data.data.total;
          this.table.data = res.data.data.records;
          //if (this.event === "group"){
            this.table.data.forEach(item=>{
              if (!!item.groupIds){
                item.groupIds.split(",").forEach((id)=>{
                  if (id == _this.groupId){
                    item["_disabled"] = true;
                  }else{
                    item["_disabled"] = false;
                  }
                })
              }
            })
          //}
          },);

      })
    },
    openDialog(groupId){
      //this.event = event;
      this.groupId = groupId;
      this.modal.show = true;
      this.getData();
      //console.log("ZzdUserManager.openDialog：after getData()")
    },
    close(){
      this.modal.show = false;
    },
    rowclick(row){;}
  },
  mounted() {

  }
}
</script>
